<?php

function getLngLat($address) {
    header('Content-type: text/html; charset=utf-8');
    $url = 'http://api.map.baidu.com/geocoder/v2/?address='.$address.'&output=json&ak=EB4474b9a2767eb3c9351629dffd5fc3&callback=showLocation';
    $content=file_get_contents($url);
    $content = str_replace('showLocation&&showLocation(', '', $content);
    $content = str_replace(')', '', $content);
    $data=json_decode($content,true);
//	dump($data);
    return $data['result']['location'];
}
function getpostoname($lat, $lng){
//    $lat=$this->_get('lat');
//    $lng=$this->_get('lng');
    $url="http://api.map.baidu.com/geocoder/v2/?ak=EB4474b9a2767eb3c9351629dffd5fc3&callback=&location={$lat},{$lng}&output=json&pois=0";
    $content=file_get_contents($url);
    $data=json_decode($content,true);
	return $data;
//    echo $content;
}
function get_qq_map($latitude, $longitude){
    $ret = '';
    $q = 'http://apis.map.qq.com/ws/geocoder/v1/?location='.$latitude.','.$longitude.'&coord_type=1&get_poi=0&key=JWRBZ-3ZU3S-27POL-6BXRT-Q6PEH-HZBVK';
    $r = file_get_contents($q);
    $r = json_decode($r, true);
    if (@$r['result']['formatted_addresses']['recommend']) {
        return $r['result']['formatted_addresses']['recommend'];
    } elseif (@$r['result']['address_reference']['landmark_l2']) {
        return $r['result']['address_reference']['landmark_l2'];
    } else {
        return $r['result']['address'];
    }
//    dump($r['result']['address'].'('.$r['result']['formatted_addresses']['recommend'].')');
}
function qq_map_zb($latitude, $longitude){
    $ret = [];
    //腾讯地图坐标转换官网：http://lbs.qq.com/webservice_v1/guide-convert.html
    $q = "http://apis.map.qq.com/ws/coord/v1/translate?locations=".$latitude.",".$longitude."&type=1&key=JWRBZ-3ZU3S-27POL-6BXRT-Q6PEH-HZBVK";
    $resultQ = json_decode(file_get_contents($q),true);
    $ret['lat'] = $resultQ["locations"][0]["lat"];
    $ret['lng'] = $resultQ["locations"][0]["lng"];
    return $ret;
}
function ad_user_qrcode_check($user) {
    $ret = FALSE;
    $user = is_array($user) ? $user : user_get($user);
    $ad = db_get_list('advertisers', ['status' => 0]);
    $ret_i = 0;
    foreach ($ad as $ad_v) {
        $is_ad_user_qrcode = db_get_obj('ad_user_qrcode', ['uid' => $user['id'], 'ad_id' => $ad_v['id']]);
        if(!$is_ad_user_qrcode) {
            $ret_i++;
        }
    }
    if($ret_i == 0) {
        $ret = TRUE;
    }
    return $ret;
}
function ad_user_qrcode_save($qrcode) {
    $ad_recored = db_get_obj('advertisement_records', ['id' => $qrcode['ad_recored_id']]);
    $is_ad_user_qrcode = db_get_obj('ad_user_qrcode', ['uid' => $qrcode['scan_uid'], 'ad_id' => $ad_recored['ad_id']]);
    if(!$is_ad_user_qrcode) {
        db_insert('ad_user_qrcode', ['uid' => $qrcode['scan_uid'], 'ad_id' => $ad_recored['ad_id'], 'ctime' => time()]);
    }
    return '';
}

function qrcode_to_bigbackground($ad_records) {
    $qrcode = db_get_obj('qrcode', ['id' => 1]);
    $ad_records = is_array($ad_records) ? $ad_records : db_get_obj('advertisement_records', ['id' => $ad_records]);
    $img_qrcode = imagecreatefromstring(file_get_contents($qrcode['qrcode_url']));
    $img_backgound = imagecreatefromstring(file_get_contents($ad_records['background']));
    imagecopyresampled($img_qrcode, $img_qrcode, 0, 0, 0, 0, $ad_records['qrcode_wh'], $ad_records['qrcode_wh'], 430, 430);
    imagecopymerge($img_backgound, $img_qrcode, $ad_records['bg_x'], $ad_records['bg_y'], 0, 0, $ad_records['qrcode_wh'], $ad_records['qrcode_wh'], 100);
    ob_clean();
    header('Content-Type:image/jpeg');
    imagejpeg($img_backgound, null, 10);
    exit;
}

/**
 *
 */
function qrcode_get_file_name ( $qr_code ) {
    return 'cache/qrcodeimage/'.$qr_code['id'].'.jpg';
}
function qrcode_2_bigbackground($qr_code, $filename) {
    if($qr_code['type'] == 2) {
        $qr_code['ad_recored_id'] = 1;
        $img_backgound = imagecreatefromstring(file_get_contents('assets/advertised_background/'.$qr_code['ad_recored_id'].'.png'));
    } else {
        $img_backgound = imagecreatefromstring(file_get_contents('assets/advertised_background/0.png'));
    }
    $img_qrcode = imagecreatefromstring(file_get_contents($qr_code['qrcode_url']));
    $reload_format = [
        0 => [
            'wh' => 308,
            'x' => 158,
            'y' => 330,
        ],
        1 => [
            'wh' => 318,
            'x' => 791,
            'y' => 260,
        ],
        2 => [
            'wh' => 380,
            'x' => 276,
            'y' => 232,
        ]
    ];

    imagecopyresampled($img_qrcode, $img_qrcode, 0, 0, 0, 0, $reload_format[$qr_code['ad_recored_id']]['wh'], $reload_format[$qr_code['ad_recored_id']]['wh'], 430, 430);
    imagecopymerge($img_backgound, $img_qrcode, $reload_format[$qr_code['ad_recored_id']]['x'], $reload_format[$qr_code['ad_recored_id']]['y'], 0, 0, $reload_format[$qr_code['ad_recored_id']]['wh'], $reload_format[$qr_code['ad_recored_id']]['wh'], 100);
    ob_clean();
    imagejpeg($img_backgound, $filename, 80);
    return '';
}
function qrcode_file_maker( $qr_code ) {
    $ret = qrcode_get_file_name($qr_code);
    if( !file_exists($ret) ) {
        qrcode_2_bigbackground($qr_code, $ret);
    }
    if( !file_exists($ret) ) {
        $ret = false;
    }
    return $ret;
}
function qrcode_file_md5( $qr_code ) {
    return md5_file(qrcode_file_maker( $qr_code) );
}
function qrcode_file_download_url( $qr_code, $device ) {
	$signature = new AndriodApiSignauture($device['private_key']);
	$a = [
        'nonce_str' =>  md5(uniqid(microtime())),
		'serial_number' =>  $device['serial_number'],
	];
	$paramater = $signature->createLinkstring($a);
	$ret = site_url('api/v3/device/qrcode/image/'.$qr_code['id']).'?'.$paramater.'&sign='.$signature->buildRequestMysign($a);
	return $ret;
}
//Y-m-d -> Ymd
function get_day_int($day){
    return date('Ymd',strtotime($day));
}
//Ymd -> Y-m-d
function get_date($day){
    return substr($day, 0, 4).'-'.substr($day, 4, 2).'-'.substr($day, 6, 2);
}

define('EARTH_RADIUS', 6378.137);//地球半径
define('PI', 3.1415926);
/**
 * 计算两组经纬度坐标 之间的距离
 * params ：lat1 纬度1； lng1 经度1； lat2 纬度2； lng2 经度2； len_type （1:m or 2:km);
 * return m or km
 */
function get_distance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2)
{
    $radLat1 = $lat1 * PI / 180.0;
    $radLat2 = $lat2 * PI / 180.0;
    $a = $radLat1 - $radLat2;
    $b = ($lng1 * PI / 180.0) - ($lng2 * PI / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $s = $s * EARTH_RADIUS;
    $s = round($s * 1000);
    $unit = 'm';
    if ($s > 1000) {
        $s /= 1000;
        $unit = 'km';
    }
//    if ($len_type > 1) {
//        $s /= 1000;
//    }
    return round($s, $decimal).$unit;
}





function W($id) {

    $w = 'cid in('.$id;

    $wr = db_get_list('c_cat','fid='.$id, '', '', '', 'id');

    foreach ($wr as $v) {

        $w .= ','.$v['id'];

        $wr2 = db_get_list('c_cat','fid='.$v['id'], '', '', '', 'id');

        foreach ($wr2 as $v2) {

            $w .= ','.$v2['id'];

        }

    }

    $w .= ')';

    return $w;

}

function Tid($arr) {

    $w = 'id in(';

    $i = 0;

    foreach ($arr as $v) {

        $w .= $v['sid'];

        if (count($arr)-1 > $i)$w .= ',';

        $i++;

    }

    $w .= ')';

    return $w;

}
function tag_title($tag_id,$short='tag_id'){

    if (!$tag_id)return false;

    $gb = & get_instance();

    $tag_id = explode(',', $tag_id);

    $tag_title = '';

// 	$tag = $gb->config->item($short);

    $tag = $gb->config->item('tag_id');

    $i = 1;

    foreach ($tag_id as $v) {

        $tag_title .= '<a target="_blank" href="'.site_url('i/tag/'.$v).'" class="tag_title tag_'.$i;

        if ($i==1)$tag_title .= ' tag_s';

        if ($i==count($tag_id))$tag_title .= ' tag_e';

// 		$tag_title .= '">'.$tag[$v].'</a>';

        if ($short == 'tag_id_short'){

            $tag_title .= '">'.mb_substr($tag[$v], -1,1,'utf-8').'</a>';

        }else {

            $tag_title .= '">'.$tag[$v].'</a>';

        }

        $i++;

    }

    return $tag_title;

}

function pdlx($type=0) {

    $str = '';

    if ($type == 1){

        $str = '单页';

    }elseif ($type == 2){

        $str = '图片列表';

    }elseif ($type == 3){

        $str = '新闻列表';

    }

    return $str;

}

function unescape($str){

    $ret = '';

    $len = strlen($str);

    for ($i = 0; $i < $len; $i++){

        if ($str[$i] == '%' && $str[$i+1] == 'u'){

            $val = hexdec(substr($str, $i+2, 4));

            if ($val < 0x7f) $ret .= chr($val);

            else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));

            else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));

            $i += 5;

        }

        else if ($str[$i] == '%'){

            $ret .= urldecode(substr($str, $i, 3));

            $i += 2;

        }

        else $ret .= $str[$i];

    }

    return $ret;

}

//过滤标点符号

function guolvbiaodian($str) {

    $str=urlencode($str);//将关键字编码

    $str=preg_replace("/(%7E|%60|%21|%40|%23|%24|%25|%5E|%26|%27|%2A|%28|%29|%2B|%7C|%5C|%3D|\-|_|%5B|%5D|%7D|%7B|%3B|%22|%3A|%3F|%3E|%3C|%2C|\.|%2F|%A3%BF|%A1%B7|%A1%B6|%A1%A2|%A1%A3|%A3%AC|%7D|%A1%B0|%A3%BA|%A3%BB|%A1%AE|%A1%AF|%A1%B1|%A3%FC|%A3%BD|%A1%AA|%A3%A9|%A3%A8|%A1%AD|%A3%A4|%A1%A4|%A3%A1|%E3%80%82|%EF%BC%81|%EF%BC%8C|%EF%BC%9B|%EF%BC%9F|%EF%BC%9A|%E3%80%81|%E2%80%A6%E2%80%A6|%E2%80%9D|%E2%80%9C|%E2%80%98|%E2%80%99)+/",'',$str);

    $str=urldecode($str);//将过滤后的关键字解码

    return $str;

}

//将日期转换成周几

function _get_chinese_weekday($datetime){

    $weekday  = date('w', strtotime($datetime));

    $weeklist = array('日', '一', '二', '三', '四', '五', '六');

    return '周' . $weeklist[$weekday];

}

//计算两个日期差

function _daysbetweendates($starttime,$endtime){

    $starttime = strtotime($starttime);

    $endtime = strtotime($endtime);

    $chatime = abs($endtime - $starttime);

    $day = floor($chatime/(3600*24));

    $chatime = $chatime%(3600*24);//除去整天之后剩余的时间

    $hour = floor($chatime/3600);

    $chatime = $chatime%3600;//除去整小时之后剩余的时间

    $minute = floor($chatime/60);

//		$second = $chatime%60;//除去整分钟之后剩余的时间

//	    return $day.'天'.$hour.'小时'.$minute.'分'.$second.'秒';

    return $day.'天'.$hour.'小时';

}